package concurrecy.util;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

class JannaCountDownLatch {

    private final Sync sync;

    public JannaCountDownLatch(int count) {
        this.sync = new Sync(count);
    }

    public void countDown() {
        sync.releaseShared(1);
    }

    public void await() {
        sync.acquireShared(1);
    }

    private class Sync extends AbstractQueuedSynchronizer {
        public Sync(int count) {
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int arg) {
            return getState() == 0 ? 1 : -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            int s, n;
            do {
                s = getState();
                if(s == 0)
                    return false;
                n = s - 1;
            } while(!compareAndSetState(s, n));
            return n == 0;
        }
    }
}

class CountDownTask1 implements Runnable {
    private JannaCountDownLatch latch;
    private Random random = new Random();

    public CountDownTask1(JannaCountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public String toString() {
        return Thread.currentThread().getName();
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(random.nextInt(10000));
            latch.countDown();
            System.out.println(this + " task completed");
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
    }
}

public class MyCountDownLatchDemo {
    final static int SIZE = 10;
    public static void main(String[] args) throws InterruptedException {
        JannaCountDownLatch latch = new JannaCountDownLatch(SIZE);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < SIZE; i++) {
            service.execute(new CountDownTask1(latch));
        }
        latch.await();
        System.out.println("all task is completed");
        service.shutdown();
    }
}
